<template>
  <a-card class="profile-container">
    <div class="profile-header">
      <a-avatar :size="120" class="profile-avatar">
        <img v-if="user.userAvatar" :src="user.userAvatar" />
        <icon-user v-else />
      </a-avatar>
      <div class="profile-info">
        <h2>{{ user.userName || "未设置昵称" }}</h2>
        <a-tag :color="roleColor">{{ roleName }}</a-tag>
        <p class="profile-account">用户id: {{ user.id }}</p>
      </div>
    </div>

    <a-tabs default-active-key="1">
      <a-tab-pane key="1" title="基本信息">
        <a-descriptions :column="1" bordered>
          <a-descriptions-item label="性别">
            {{ genderMap[user.gender] || "未设置" }}
          </a-descriptions-item>
          <a-descriptions-item label="个人简介">
            {{ user.userProfile || "暂无简介" }}
          </a-descriptions-item>
          <a-descriptions-item label="注册时间">
            {{ formatDate(user.createTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="最后更新时间">
            {{ formatDate(user.updateTime) }}
          </a-descriptions-item>
        </a-descriptions>
      </a-tab-pane>
      <a-tab-pane key="2" title="修改信息">
        <a-form :model="editForm" layout="vertical">
          <a-form-item label="头像">
            <a-upload
              action="/"
              :fileList="file ? [file] : []"
              :show-file-list="false"
              @change="onChange"
              :custom-request="uploadAvatar"
              :before-upload="beforeUpload"
            >
              <template #upload-button>
                <a-avatar :size="100">
                  <img
                    v-if="userAvatarImg || user.userAvatar"
                    :src="userAvatarImg || user.userAvatar"
                  />
                  <icon-user v-else />
                </a-avatar>
              </template>
            </a-upload>
          </a-form-item>
          <a-form-item label="昵称" field="userName">
            <a-input v-model="editForm.userName" placeholder="请输入昵称" />
          </a-form-item>
          <a-form-item label="性别" field="gender">
            <a-radio-group v-model="editForm.gender">
              <a-radio :value="0">男</a-radio>
              <a-radio :value="1">女</a-radio>
              <a-radio :value="2">保密</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="个人简介" field="userProfile">
            <a-textarea
              v-model="editForm.userProfile"
              placeholder="介绍一下自己吧"
              :max-length="200"
              show-word-limit
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleSave">保存修改</a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>
  </a-card>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useStore } from "vuex";
import { Message } from "@arco-design/web-vue";
import { IconUser } from "@arco-design/web-vue/es/icon";
import { UserControllerService } from "../../../generated";
import ACCESS_ENUM from "@/access/accessEnum";
import dayjs from "dayjs";
import { FileControllerService } from "../../../generated";

const store = useStore();
const user = computed(() => store.state.user.loginUser);
const file = ref();
const userAvatarImg = ref("");
const editForm = ref({
  userName: "",
  gender: 0,
  userProfile: "",
});

// 角色映射
const roleName = computed(() => {
  switch (user.value.userRole) {
    case ACCESS_ENUM.ADMIN:
      return "管理员";
    case ACCESS_ENUM.USER:
      return "普通用户";
    default:
      return "未知角色";
  }
});

// 角色颜色
const roleColor = computed(() => {
  switch (user.value.userRole) {
    case ACCESS_ENUM.ADMIN:
      return "red";
    case ACCESS_ENUM.USER:
      return "blue";
    default:
      return "gray";
  }
});

// 性别映射
const genderMap = {
  0: "男",
  1: "女",
  2: "保密",
};

// 格式化日期
const formatDate = (date: Date | string) => {
  if (!date) return "未知";
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
};

// 加载用户数据
const loadUserData = async () => {
  try {
    const res = await UserControllerService.getLoginUserUsingGet();
    if (res.code === 0) {
      store.dispatch("user/getLoginUser", res.data);
      // 初始化编辑表单
      editForm.value = {
        userName: res.data.userName || "",
        gender: res.data.gender || 0,
        userProfile: res.data.userProfile || "",
      };
    }
  } catch (e) {
    Message.error("获取用户信息失败");
  }
};

// 保存修改

const beforeUpload = (file: File) => {
  const validTypes = ["image/jpeg", "image/png", "image/gif"];
  if (!validTypes.includes(file.type)) {
    Message.error("只支持JPEG、PNG或GIF格式的图片");
    return false;
  }
  if (file.size > 2 * 1024 * 1024) {
    Message.error("图片大小不能超过2MB");
    return false;
  }
  return true;
};

// 文件变化时的处理
const onChange = (fileItem: any) => {
  file.value = fileItem;
  // 创建本地预览URL
  if (fileItem.file) {
    userAvatarImg.value = URL.createObjectURL(fileItem.file);
  }
};

// 自定义上传逻辑
const uploadAvatar = async (options: any) => {
  const { fileItem } = options;
  if (!fileItem || !fileItem.file) {
    Message.error("请先选择有效的文件");
    return;
  }

  try {
    const formData = new FormData();
    formData.append("file", fileItem.file);

    const res = await FileControllerService.uploadFileUsingPost(formData);
    if (res.code === 0) {
      userAvatarImg.value = res.data;
      Message.success("头像上传成功");
    } else {
      Message.error("上传失败: " + (res.message || "未知错误"));
    }
  } catch (error) {
    console.error("上传错误:", error);
    Message.error("上传失败");
  }
};

// 修改保存逻辑
const handleSave = async () => {
  try {
    const res = await UserControllerService.updateUserUsingPost({
      ...editForm.value,
      id: user.value.id,
      userAvatar: userAvatarImg.value || user.value.userAvatar, // 添加头像URL
    });

    if (res.code === 0) {
      Message.success("修改成功");
      // 重置头像预览
      userAvatarImg.value = "";
      await loadUserData();
    } else {
      Message.error(res.message || "修改失败");
    }
  } catch (e) {
    Message.error("修改失败");
  }
};
onMounted(() => {
  loadUserData();
});
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid var(--color-border-2);
}

.profile-avatar {
  margin-right: 24px;
}

.profile-info h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
}

.profile-account {
  margin: 8px 0 0 0;
  color: var(--color-text-3);
}

:deep(.arco-tabs-content) {
  padding-top: 16px;
}
</style>
